import pymysql


class DBUtil(object):

    conn = None


    #获取链接
    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host='localhost', user='root', passwd='123456', db='test01', charset='utf8')
        return cls.conn

    #关闭连接
    @classmethod
    def __close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None


    # def get_cursor(self):
    #     pass



    #查询一条
    @classmethod
    def select_one(cls,sql):
        cursor = None
        res = None
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            res = cursor.fetchone()
        except Exception as e:
            print("查询sql错误：",str(e))
        finally:
            cursor.close()
            cls.__close_conn()
            return res


    #增删改
    @classmethod
    def uid_db(cls,sql):
        cursor = None
        try:
            cls.conn = cls.__get_conn()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            print("影响的行数：",cls.conn.affected_rows())

            cls.conn.commit()
        except Exception as e:
            print("修改操作失败：",str(e))

            cls.conn.rollback()
        finally:
            cursor.close()
            cls.__close_conn()



if __name__ == '__main__':
    # res = DBUtil.select_one("select * from t_book;")
    # print("查询结果为：",res)
    DBUtil.uid_db("update t_book set is_delete=1 where id = 2")